package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class HandleExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 创建一个可能失败的任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }

            // 模拟50%的失败率
            if (Math.random() > 0.5) {
                throw new RuntimeException("任务执行失败");
            }

            return "任务执行成功";
        });

        // handle: 无论成功还是失败都会执行，可以同时访问结果和异常
        CompletableFuture<String> handledFuture = future.handle((result, ex) -> {
            System.out.println("handle执行线程: " + Thread.currentThread().getName());

            if (ex != null) {
                System.err.println("任务失败: " + ex.getMessage());
                return "恢复后的默认值";
            } else {
                System.out.println("任务成功: " + result);
                return result.toUpperCase();
            }
        });

        System.out.println("处理后的结果: " + handledFuture.get());
        System.out.println("主线程结束");
    }
}
